package edu.hawaii.ics414;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class DataRequester {
  public DataRequester() {

  }

  public String getData(String url) {
    try {
      HttpClient httpClient = new DefaultHttpClient();
      HttpResponse response = httpClient.execute(new HttpPost(url));
      HttpEntity entity = response.getEntity();

      // convert response to string
      return getHttpContent(entity.getContent());
    }
    catch (Exception e) {
      Log.e("log_tag", "Error in http connection " + e.toString());
      return "Failed";
    }
  }

  private String getHttpContent(InputStream isr) {
    String result = "";
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      isr.close();

      result = sb.toString();
    }
    catch (Exception e) {
      Log.e("log_tag", "Error converting result " + e.toString());
    }
    return result;
  }

  public void POST() {
    try {
      // Construct data
      String data =
          URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
      data +=
          "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

      // Send data
      URL url = new URL("http://localhost/TUT/POSTDATA/post.php");
      URLConnection conn = url.openConnection();
      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
      wr.write(data);
      wr.flush();

      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }
      wr.close();
      rd.close();
    }
    catch (Exception e) {

    }

  }
}
